package com.comum.javahomework420242025.controller;

import com.comum.javahomework420242025.pojo.*;
import com.comum.javahomework420242025.repository.AllFileRepository;
import com.comum.javahomework420242025.repository.CompanyInfoRepository;
import com.comum.javahomework420242025.utils.MyFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
public class CompanyInfoController {
    @Autowired
    private AllFileRepository allFileRepository;
    @Autowired
    private CompanyInfoRepository companyInfoRepository;
    @PostMapping("/addCompanyInfo")
    public Result addCompanyInfo(@RequestBody CompanyInfo companyInfo){
        companyInfo.setId(null);

        companyInfoRepository.save(companyInfo);
        return Result.success();
    }
    @PutMapping("/updateCompanyInfo")
    public Result updateCompanyInfo(@RequestBody CompanyInfo companyInfo){

        companyInfoRepository.save(companyInfo);
        return Result.success();
    }
    @DeleteMapping("/deleteCompanyInfo")
    public Result deleteCompanyInfo(String id){
        System.out.println(id);
        companyInfoRepository.deleteById(Long.valueOf(id));
        String type = "公司信息";
        allFileRepository.deleteByElseIdAndType(id,type);
        return Result.success();
    }
    @PostMapping("/getCompanyInfo")
    public Result<PageBean<CompanyInfo>> getCompanyInfo(@RequestBody AskList askList){
        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        String type = askList.getFindType();
        PageBean<CompanyInfo> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<CompanyInfo> page = companyInfoRepository.list(str,pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());
        System.out.println(pb);
        return Result.success(pb);


    }
    @PostMapping("/uploadCompanyInfoFile") //产品管理上传文件
    public Result uploadCompanyInfoFile(String elseid,@RequestPart("files") MultipartFile[] files){
        for (MultipartFile file : files) {
            String fileName = MyFileUtil.uploadfile(file);
            AllFile allFile =new AllFile(null,Long.parseLong(elseid),"公司信息",fileName);
            allFileRepository.save(allFile);
        }
        return Result.success();
    }
    @GetMapping("/getLoadCompanyInfoFileName")
    public Result<List<String>>getloadfilename(String elseid){
        String type = "公司信息";
        List<String> res = allFileRepository.findfilenames(elseid,type);
        return Result.success(res);
    }

}
